package com.zhihuichongcheng.application.ui.cricle.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.FileUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.cricle.CricleTypeBean;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.cricle.adapter.AddImageAdapter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by 3water on 2016/10/30.
 */

public class AddCricleActivity extends BaseActivity implements View.OnClickListener {
    private final int REQUEST_TYPE = 0;
    private String mUpdateIconCameraPath;
    private Uri mImUri;
    private String mPath;
    private AddImageAdapter mAdapter;
    private RecyclerView mRcvAddImg;
    private List<String> mList = new ArrayList<>();
    private UserBean mUser;
    private List<String> mPathList = new ArrayList<>();
    private int index = 0;
    private TextView mTvSelect;
    private EditText mEtTitle, mEtContent;
    private CricleTypeBean bean;
    private List<CricleTypeBean> mListType;
    private RelativeLayout mRlType;
    private int width;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_cricle);
        initView();
        initData();
    }

    private void initView() {
        setSystemBarColor(R.color.activity_color);
        setTitle("发帖");
        setTvRight("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mEtContent.getText().toString();
                String title = mEtTitle.getText().toString();
                if (!check(content, title)) return;
                if (bean != null) {
                    DialogUtil.showLoadDiadlog(mContext);
                    if (mList.size() > 0) {
                        String path = "";
                        for (int i = 0; i < mList.size(); i++) {
                            if (i == 0) {
                                path += mList.get(i);
                            } else {
                                path += "," + mList.get(i);
                            }
                        }
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("content", content);
                        params.put("title", title);
                        params.put("jinbaoHomeCategoryId", bean.getJinbaoHomeCategoryId());
                        params.put("imgUrl", path);
                        params.put("token", mUser.getToken());
                        mManager.post(NetworkAPI.CricleSave, new HttpCallback() {
                            @Override
                            public void onSuccess(int code, String value, String msg) {
                                LogUtil.logD(value);
                                DialogUtil.dismiss(mContext);
                                setResult(Activity.RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onFailure(String value) {
                                DialogUtil.dismiss(mContext);
                                ToastOpt.createToast(mContext, "发布失败");
                            }
                        }, params);
                    } else {
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("content", content);
                        params.put("title", title);
                        params.put("jinbaoHomeCategoryId", bean.getJinbaoHomeCategoryId());
                        params.put("token", mUser.getToken());
                        mManager.post(NetworkAPI.CricleSave, new HttpCallback() {
                            @Override
                            public void onSuccess(int code, String value, String msg) {
                                LogUtil.logD(value);
                                DialogUtil.dismiss(mContext);
                                setResult(Activity.RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onFailure(String value) {
                                DialogUtil.dismiss(mContext);
                                ToastOpt.createToast(mContext, "发布失败");
                            }
                        }, params);
                    }
                } else {
                    ToastOpt.createToast(mContext, "请选择类型");
                }
            }
        });
        mRlType = (RelativeLayout) findViewById(R.id.rl_type);
        //改变一下布局
        width = DeviceUtil.getWidth(mContext);
        width = width - DeviceUtil.dip2px(mContext, 20);
        mRcvAddImg = (RecyclerView) findViewById(R.id.rcv_img);
        mAdapter = new AddImageAdapter(mContext);
        mRcvAddImg.setLayoutManager(new GridLayoutManager(mContext, 4));
        mRcvAddImg.setAdapter(mAdapter);
        changeRcvSize();
        mAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.showUploadFile(mContext, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        getImageFromCamera();
                    }
                }, new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        selectImageFromAlbum();
                    }
                });
            }
        });
        mAdapter.setData("");
        mAdapter.notifyDataSetChanged();
        mTvSelect = (TextView) findViewById(R.id.tv_selectType);
        mEtTitle = (EditText) findViewById(R.id.et_title);
        mEtContent = (EditText) findViewById(R.id.et_content);
        mRlType.setOnClickListener(this);
    }

    private void initData() {
        mUser = app.getUser();
        loadCategoryId();
    }

    private boolean check(String content, String title) {
        if (StringUtil.isEmpty(title)) {
            ToastOpt.createToast(this, "请输入标题");
            return false;
        }
        if (StringUtil.isEmpty(content)) {
            ToastOpt.createToast(this, "请输入内容");
            return false;
        }
        return true;
    }

    private void changeRcvSize() {
        if (mAdapter.getItemCount() < 5) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 4 + DeviceUtil.dip2px(mContext, 5));
            params.gravity = Gravity.CENTER;
            mRcvAddImg.setLayoutParams(params);
        } else if (mAdapter.getItemCount() < 9) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 2 + DeviceUtil.dip2px(mContext, 10));
            params.gravity = Gravity.CENTER;
            mRcvAddImg.setLayoutParams(params);
        } else if (mAdapter.getItemCount() == 9) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 4 * 3 + DeviceUtil.dip2px(mContext, 15));
            params.gravity = Gravity.CENTER;
            mRcvAddImg.setLayoutParams(params);
        }
    }

    /***
     * 拍照
     */
    private void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        mUpdateIconCameraPath = Constants.Const_Cache_Dir + "/" + System.currentTimeMillis() + ".jpg";
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir = new File(Constants.Const_Cache_Dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File f = new File(mUpdateIconCameraPath);
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, Constants.REQUESTCODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(mContext, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册选择
     */
    private void selectImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, Constants.REQUESTCODE_ALBUM);
    }

    private void loadCategoryId() {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", mUser.getToken());
        mManager.post(NetworkAPI.CricleCategorys, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                mListType = GsonUtil.paraeFromStringToList(value, CricleTypeBean.class);
            }

            @Override
            public void onFailure(String value) {

            }
        }, map);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_type:
                if (mListType.size() > 0) {
                    Intent intent = new Intent(mContext, CricleTypeActivity.class);
                    intent.putParcelableArrayListExtra("list", (ArrayList) mListType);
                    startActivityForResult(intent, REQUEST_TYPE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUESTCODE_CAPTURE_CAMEIA:
                if (resultCode == Activity.RESULT_OK) {
                    initCrope(Uri.fromFile(new File(mUpdateIconCameraPath)));
                }
                break;
            case Constants.REQUESTCODE_ALBUM:
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = null;
                    mUpdateIconCameraPath = data.getData().getPath();
                    if (FileUtil.checkFileByType(mUpdateIconCameraPath, "img")) {

                    } else {
                        uri = data.getData();
                        mUpdateIconCameraPath = getRealPathFromURI(uri);
                    }
                    initCrope(Uri.fromFile(new File(mUpdateIconCameraPath)));
                }
                break;
            case Constants.REQUESTCODE_CHOOSE_PIC:
                if (data != null) {
                    mUpdateIconCameraPath = mPath;
                    mAdapter.setData(mUpdateIconCameraPath);
                    mAdapter.notifyDataSetChanged();
                    changeRcvSize();
                    mPath = Constants.Const_Cache_Dir + "/aaa" + (mAdapter.getItemCount() - 1) + ".jpg";
                    convertToJpg(mUpdateIconCameraPath, mPath);
                }
                break;
            case REQUEST_TYPE:
                if (data != null && data.hasExtra("id")) {
                    bean = data.getParcelableExtra("id");
                    mTvSelect.setText(bean.getCategoryName());
                }

                break;
            default:
                break;
        }
    }

    private void initCrope(Uri imageUri) {
        mPath = Constants.Const_Cache_Dir + "/" + System.currentTimeMillis() + ".jpg";
        File file = new File(mPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mImUri = Uri.fromFile(file);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        if (Build.MODEL.contains("PLK")) {
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }

        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 800);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);
        startActivityForResult(intent, Constants.REQUESTCODE_CHOOSE_PIC);
    }

    private String getRealPathFromURI(Uri contentUri) { //传入图片uri地址
        String path = "";
        Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();
            cursor = mContext.getContentResolver().query(
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
            if (cursor != null) {
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
            }
        }
        return path;
    }

    public void convertToJpg(String pngFilePath, String jpgFilePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(pngFilePath, options);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(jpgFilePath));
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos)) {
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateOss(app.getOss(), jpgFilePath);
    }

    private void updateOss(final OSS oss, final String path) {
        index++;
        mUser = app.getUser();
        if (mUser == null) {
            ToastOpt.createToast(mContext, "请先登陆");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Random random = new Random(1000);//指定种子数字
                final String name = System.currentTimeMillis() + random.nextInt() + ".jpg";
                // 构造上传请求
                PutObjectRequest put = new PutObjectRequest("yirimao", name, path);
                try {
                    PutObjectResult putResult = oss.putObject(put);
                    LogUtil.logD(Constants.OSS_ENDPOINT + "/" + name);
                    mList.add(Constants.OSS_ENDPOINT + "/" + name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
